#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import serial
import time
import json

serialT = None
serialT2 = None

def readPort(port = 3):
    global serialT,serialT2
    time.sleep(0.003)
    if port == 1:
        n = serialT.inWaiting()
        # print(n)
        if n > 0:
            pstr = serialT.read(n)
            print('setial1 read:%s'%(str(pstr)))
    elif port == 2:
        n = serialT2.inWaiting()
        # print(n)
        if n > 0:
            pstr = serialT2.read(n)
            print('setial2 read:%s'%(str(pstr)))
    else:
        n = serialT.inWaiting()
        if n > 0:
            pstr = serialT.read(n)
            print('setial1 read:%s'%(str(pstr)))
        n = serialT2.inWaiting()
        if n > 0:
            pstr = serialT2.read(n)
            print('setial2 read:%s'%(str(pstr)))
def readPort1():
    readPort(1)

def readPort2():
    readPort(2)

def sendCmd(pcmd,port = 3):
    global serialT,serialT2
    back = None
    if port == 1:
        back = serialT.write(pcmd.encode())
        serialT.flush()
    elif port == 2:
        back = serialT2.write(pcmd.encode())
        serialT2.flush()
    else:
        back = serialT.write(pcmd.encode())
        serialT.flush()
        back = serialT2.write(pcmd.encode())
        serialT2.flush()
    print('serial %d->send cmd,:%s,isOk:%s'%(port,pcmd,str(back)))
    return back

def sendCmd1(pcmd):
    sendCmd(pcmd,1)

def sendCmd2(pcmd):
    sendCmd(pcmd,2)

def initSerial():
    global serialT,serialT2
    f = open('config.txt','r')
    jstr = f.read()
    f.close()
    jdic = json.loads(jstr)
    serialT = serial.Serial(jdic['port'],jdic['btv'],timeout=0.5)
    serialT2 = serial.Serial(jdic['port2'],jdic['btv'],timeout=0.5)
    time.sleep(2)
    sendCmd('@')
    readPort()
    sendCmd('<FFFF>')
    time.sleep(1)
            